<template>
  <div class="websocket-test">
    <van-row justify="space-around" :wrap="true">
      <van-col span="8">
        <!-- 服务器配置 -->
        <van-cell-group :title="`服务器配置 状态: ${connectionStatus}`">
          <van-field v-model="wsUrl" size="normal" label="地址" placeholder="请输入WebSocket地址">
            <template #button>
              <van-button
                :type="isConnected ? 'danger' : 'primary'"
                size="small"
                @click="openConnection"
              >
                {{ isConnected ? '关闭连接' : '开启连接' }}
              </van-button>
            </template>
          </van-field>
          <!-- <van-button type="danger" @click="toggleConnection">{{
            isConnected ? '关闭连接' : '开启连接'
          }}</van-button> -->
        </van-cell-group>

        <!-- 定时消息 -->
        <van-cell-group title="定时循环消息">
          <van-field v-model="interval" size="normal" label="每隔（秒）" placeholder="秒" />
          <van-field
            v-model="content"
            type="textarea"
            :autosize="true"
            label="发送内容"
            placeholder="请输入要发送的定时循环内容"
          />
          <van-button type="primary" block @click="startSending">开始发送</van-button>
          <!-- <van-field
            v-model="sendContent"
            label="需要发送到服务端的内容"
            placeholder="输入要发送的消息"
          /> -->
          <!-- <van-checkbox v-model="clearInput" shape="square">发包清空输入</van-checkbox> -->
          <!-- <van-button type="success" block @click="sendMessage">发送到服务端</van-button> -->
        </van-cell-group>
      </van-col>
      <van-col span="8">
        <!-- 常规消息 -->
        <van-cell-group title="常规消息">
          <van-field
            v-model="sendContent"
            label="消息"
            type="textarea"
            placeholder="输入要发送的消息"
            :autosize="true"
            style="min-height: 213px"
          />
          <van-button type="success" block @click="onSendMsg">发送</van-button>
        </van-cell-group>
      </van-col>
      <van-col span="8">
        <!-- 消息记录 -->
        <van-cell-group title="消息记录">
          <div>
            <van-button
              type="danger"
              icon="delete-o"
              size="small"
              @click="clearMessages"
            ></van-button>
            <!-- <van-icon name="delete-o" @click="clearMessages" /> -->
          </div>
          <div class="message-body">
            <div v-for="(msg, index) in messages" :key="index" class="message-item">
              <span>{{ msg.time }} => </span>
              <span
                :class="{
                  received: msg.type === 'received',
                  sent: msg.type === 'sent',
                  closed: msg.type === 'closed',
                }"
                >{{ msg.content }}</span
              >
            </div>
          </div>
        </van-cell-group>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import { showToast } from 'vant'
export default {
  data() {
    return {
      wsUrl: localStorage.getItem('wsUrl') || '', // 从 localStorage 读取 wsUrl，默认为空字符串
      interval: localStorage.getItem('interval') || 50, // 从 localStorage 读取 interval，默认为 50 秒
      content: localStorage.getItem('content') || '', // 从 localStorage 读取 content，默认为空字符串
      sendContent: '',
      clearInput: false,
      isConnected: false,
      connectionStatus: '未连接',
      messages: [],
      socket: null,
      timer: null,
    }
  },
  methods: {
    openConnection() {
      // 增加是否已连接的判断逻辑
      if (this.isConnected) {
        this.closeConnection()
      } else {
        if (!this.wsUrl) {
          return showToast('请输入 WebSocket 地址')
        }
        this.socket = new WebSocket(this.wsUrl)
        this.socket.onopen = () => {
          this.isConnected = true
          this.connectionStatus = '连接成功'
          this.messages.push({
            time: new Date().toLocaleTimeString(),
            content: '初始化完成',
            type: 'sent',
          })
          localStorage.setItem('wsUrl', this.wsUrl) // 将 wsUrl 缓存到 localStorage
        }
        this.socket.onmessage = (event) => {
          const message = JSON.parse(event.data)
          this.messages.push({
            time: new Date().toLocaleTimeString(),
            content: JSON.stringify(message),
            type: 'received',
          })
        }
        this.socket.onclose = () => {
          this.isConnected = false
          this.connectionStatus = '已断开'
        }
      }
    },
    closeConnection() {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        this.socket.close()
        this.messages.push({
          time: new Date().toLocaleTimeString(),
          content: '关闭连接',
          type: 'closed',
        })
      }
    },
    startSending() {
      if (!this.content) {
        return showToast('请输入要发送的内容')
      }
      // 缓存定时消息下次使用
      localStorage.setItem('content', this.content)
      // 缓存间隔时间
      localStorage.setItem('interval', this.interval)
      // 清除之前的定时器
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        this.sendMessage(this.content)
      }, this.interval * 1000)
    },
    onSendMsg() {
      if (this.sendContent) {
        this.sendMessage(this.sendContent)
      } else {
        showToast('请输入要发送的消息')
      }
    },
    sendMessage(content = null) {
      if (!content) {
        return showToast('请输入要发送的消息')
      }
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        this.socket.send(content)
        this.messages.push({
          time: new Date().toLocaleTimeString(),
          content: content,
          type: 'sent',
        })
        if (this.clearInput) {
          this.sendContent = ''
        }
      } else {
        showToast('WebSocket 未连接或已关闭')
      }
    },
    clearMessages() {
      this.messages = []
    },
  },
  beforeUnmount() {
    this.closeConnection()
    clearInterval(this.timer)
  },
}
</script>

<style scoped>
.websocket-test {
  padding: 10px;
}
.message-body {
  /* 1px 的实线边框 */
  border: 1px solid #e0e0e0;
  padding: 5px 0;
  overflow-y: auto;
  height: 600px;
}
.message-item {
  margin-bottom: 5px;
}
.received {
  color: #007bff;
}
.sent {
  color: #28a745;
}
.closed {
  color: #dc3545;
}
</style>
